//=============================================================================
// LazyParser.NET - C# Expression Parser for .NET 2.0 
//
// Copyright (c) 2008 Philippe Leybaert
//
// Permission is hereby granted, free of charge, to any person obtaining a copy 
// of this software and associated documentation files (the "Software"), to deal 
// in the Software without restriction, including without limitation the rights 
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// copies of the Software, and to permit persons to whom the Software is 
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in 
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//=============================================================================

using System;
using System.Collections.Generic;
using System.Reflection;

namespace Activa.LazyParser
{
    public interface IDynamicObject
    {
        bool TryGetValue(string propertyName, out object value, out Type type);
    }

    public class ExtensibleObject : ExtensibleObject<object>
    {
        public ExtensibleObject(object obj) : base(obj)
        {
        }
    }

    public class ExtensibleObject<T> : IDynamicObject
    {
        private readonly T _obj;
        private readonly Dictionary<string, ValueExpression> _properties = new Dictionary<string, ValueExpression>();

        public ExtensibleObject(T obj)
        {
            _obj = obj;
        }

        public T Object
        {
            get { return _obj; }
        }


        bool IDynamicObject.TryGetValue(string propertyName, out object value, out Type type)
        {
            value = null;
            type = typeof(object);

            Type targetType = (typeof(T) == typeof(object)) ? _obj.GetType() : typeof(T);

            MemberInfo[] members = targetType.GetMember(propertyName);

            if (members.Length == 0)
            {
                PropertyInfo indexerPropInfo = targetType.GetProperty("Item", new Type[] { typeof(string) });

                if (indexerPropInfo != null)
                {
                    value = indexerPropInfo.GetValue(_obj, new object[] {propertyName});
                    type = (value != null && indexerPropInfo.PropertyType == typeof(object)) ? value.GetType() : typeof(object);

                    return true;
                }

                if (_properties.ContainsKey(propertyName))
                {
                    ValueExpression valueExpression = _properties[propertyName];

                    value = valueExpression.Value;
                    type = valueExpression.Type;

                    return true;
                }

                return false;
            }

            if (members.Length >= 1 && members[0] is MethodInfo)
            {
                value = new InstanceMethod(targetType, propertyName, _obj);
                type = typeof(InstanceMethod);

                return true;
            }

            MemberInfo member = members[0];

            if (members.Length > 1) // CoolStorage, ActiveRecord and Dynamic Proxy frameworks sometimes return > 1 member
            {
                foreach (MemberInfo mi in members)
                    if (mi.DeclaringType == _obj.GetType())
                        member = mi;
            }

            if (member is FieldInfo)
            {
                value = ((FieldInfo) member).GetValue(_obj);
                type = ((FieldInfo) member).FieldType;

                return true;
            }

            if (member is PropertyInfo)
            {
                value = ((PropertyInfo) member).GetValue(_obj, null);
                type = ((PropertyInfo) member).PropertyType;

                return true;
            }

            return false;
        }

        public void Set<TProperty>(string propertyName, TProperty value)
        {
            _properties[propertyName] = new ValueExpression(value,typeof(TProperty));
        }

        public object this[string propertyName]
        {
            get
            {
                return _properties[propertyName].Value;
            }
            set
            {
                _properties[propertyName] = new ValueExpression(value, value == null ? typeof(object) : value.GetType());
            }
        }
    }
}
